import VineUtil
import urllib2
URL_Template = "http://74.125.235.192/inputtools/request?text=%s&ime=zh-t-i0-pinyin&num=%d"
class IMEClass(VineUtil.IMEBase):
	def reset(self):
		self._list = []
		self._len = []
		self._param = 10
		self._search_text = ""
		self._page = 0
		self._matched = []
		self._matched_len = 0
		self._preedit = ""
	def __init__(self):
		self.reset()
	def DisplayResult(self,predit):
		if predit == None or len(predit) == 0 : 
			self.UpdateCandidates([])
			return
		cand = []
		for i in enumerate(predit): 
			if i[0] >= 5 : break
			cand += ["%d.%s"%((i[0]+1)%10,i[1])]
		cand[0] = "<span color=\"red\">%s</span>"%cand[0]
		self.UpdateCandidates(cand)
	def FetchPage(self):
		URL = URL_Template%(urllib2.quote(self._search_text),self._param)
		res = urllib2.urlopen(URL).read()
		print "\033[31m%s\033[0m"%res
		res = eval(res)
		if res[0] != "SUCCESS": return (None,None)
		res = res[1][0]
		predit = res[1]
		length = []
		if len(res) < 3:
			for i in predit: length += [len(res[0])]
		else: length = res[2]
		return (predit,length)
	def BuildPrecommit(self):
		text = ""
		for i in self._matched: text += i[1]
		text += self._preedit[self._matched_len:]
		return text
	def Select(self,sym,state,id):
		if self._preedit == "" : return VineUtil.FE_CLIENT
		if sym == ord(' ') : sym = ord('1')
		n = sym - ord('1') + self._page * 5
		if n >= len(self._list) : return VineUtil.FE_SUCCEED
		self._matched_len += self._len[n]
		self._matched += [(self._len[n],self._list[n])]
		if self._matched_len == len(self._preedit): 
			self.Commit(self.BuildPrecommit())
			self.reset()
			return VineUtil.FE_SUCCEED
		else: self.UpdatePrecommitText('<span color="blue">%s</span>'%self.BuildPrecommit())
		self._search_text = self.BuildPrecommit()
		self._param = 10
		self._page  = 0
		predit,length = self.FetchPage()
		self._list = predit
		self._len  = length
		self.UpdatePrecommitText('<span color="blue">%s</span>'%self.BuildPrecommit())
		self.DisplayResult(predit)
		return VineUtil.FE_SUCCEED
	def ChangePage(self,sym,state,id):
		if len(self._list) == 0 : return VineUtil.FE_CLIENT
		if sym == ord('-') :
			if self._page == 0 : return VineUtil.FE_SUCCEED
			self._page -= 1
			self.DisplayResult(self._list[self._page*5:])
		else:
			if (self._page + 1) * 5 >= len(self._list) :
				if self._param == len(self._list) :
					self._param *= 2
					self._list,self._len = self.FetchPage()
					if (self._page+1)*5 < len(self._list):
						self._page += 1
						self.DisplayResult(self._list[self._page*5:])
			else:
				self._page += 1
				self.DisplayResult(self._list[self._page*5:])
		return VineUtil.FE_SUCCEED
	def PreeditTextChanged(self,text):
		if text == "" : 
			self.Commit("")
			return 
		self._preedit = text
		if len(text) < self._matched_len : 
			self._matched_len -= self._matched[-1][0]
			self._matched = self._matched[:-1]
		self._search_text = self.BuildPrecommit()
		self._param = 10
		self._page  = 0
		predit,length = self.FetchPage()
		self._list = predit
		self._len  = length
		self.UpdatePrecommitText('<span color="blue">%s</span>'%self.BuildPrecommit())
		self.DisplayResult(predit)
	def OnEnterPressed(self,sym,state,id):
		if self._preedit == "" : return VineUtil.FE_CLIENT
		self.Commit(self._preedit)
		self.reset()
	def Enabled(self):
		self.SetTrayIcon("./image/goog.png")
		modifier = VineUtil.StateFilter(forbidden = VineUtil.IMStateAll, allowed = VineUtil.IMStateNone)
		self.RegisterForwardFilter(VineUtil.BuildKeyRange('0','9'), modifier, VineUtil.IMKeyActionPress, IMEClass.Select)
		self.RegisterForwardFilter(VineUtil.BuildKeyRange(' ',' '), modifier, VineUtil.IMKeyActionPress, IMEClass.Select)
		self.RegisterForwardFilter(VineUtil.BuildKeyRange('-','-'), modifier, VineUtil.IMKeyActionPress, IMEClass.ChangePage)
		self.RegisterForwardFilter(VineUtil.BuildKeyRange('=','='), modifier, VineUtil.IMKeyActionPress, IMEClass.ChangePage)
		self.RegisterForwardFilter((0xff0d,0xff0e), modifier, VineUtil.IMKeyActionPress, IMEClass.OnEnterPressed)
def Create(): return IMEClass()
